/**
 * Copyright (C)  Gadglet .
 *
 * This file is part of Gadglet
 *
 * Gadglet is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Gadglet is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Gadglet. If not, see <http://www.gnu.org/licenses/>.
 */

package com.gadglet.client.gwt.google;

import java.util.ArrayList;

import com.gadglet.client.gwt.core.GadgletRequestOptions;
import com.gadglet.client.gwt.ui.DebugDialogBox;
import com.gadglet.client.gwt.ui.RequestLoadingImage;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.gadgets.client.io.AuthorizationType;
import com.google.gwt.gadgets.client.io.ContentType;
import com.google.gwt.gadgets.client.io.GadgetsIo;
import com.google.gwt.gadgets.client.io.IoProvider;
import com.google.gwt.gadgets.client.io.MethodType;
import com.google.gwt.gadgets.client.io.Response;
import com.google.gwt.gadgets.client.io.ResponseReceivedHandler;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;



public  class GoogleRequest {

	protected   ArrayList <JSONObject> itemsList  = new ArrayList <JSONObject>() ;
	private   ArrayList <Headers> headersList = new ArrayList <Headers> ();
	
	private   AuthorizationType authorizationType = AuthorizationType.OAUTH;
    private   ContentType contentType= ContentType.JSON;
    private   MethodType methodType = MethodType.GET;
    private   String feedUrl  = null;
    final protected DebugDialogBox errorNotifier = DebugDialogBox.getErrorNotifier();
    final protected  RequestLoadingImage loading =RequestLoadingImage.getContentLoadingImage();
    private String authorizationMsg = null;
    public void setHeaders(String name, String value) {
		Headers item =  new Headers(name, value);
		headersList.add(item);
	}
      
    GoogleRequest getRequest(){
    	return this;
    }
    
    public void setAuthorizationMsg(String authorizationMsg){
    	this.authorizationMsg =authorizationMsg;
    }
    
    
 
	public AuthorizationType getAuthorizationType() {
		return authorizationType;
	}
	protected void setAuthorizationType(AuthorizationType authorizationType) {
		this.authorizationType = authorizationType;
	}
	public ContentType getContentType() {
		return contentType;
	}
	protected void setContentType(ContentType contentType) {
		this.contentType = contentType;
	}
	public MethodType getMethodType() {
		return methodType;
	}
	protected void setMethodType(MethodType methodType) {
		this.methodType = methodType;
	}
 
	
	
	protected void addItem(JSONObject item)
	{
		itemsList.add(item);
	}
    
	protected void clearList()
	{
		itemsList.clear();
	}
	
	public String getFeedUrl() {
			return feedUrl;
	}
	
	public void setFeedUrl(String feedUrl) {
			this.feedUrl = feedUrl;
	}
	
	public boolean callFeed()
	{
		return callFeed(null);	
	}
	public boolean callFeed(final GoogleFeedHandler handler)
	{
		
			 
		
		 if(  feedUrl == null)
			  return false;
		 
		 		  
		  String url = feedUrl;
		  final GadgletRequestOptions options = GadgletRequestOptions.newInstance().cast();
		  options.setAuthorizationType(authorizationType);
		  options.setContentType(contentType);
		  options.setMethodType(methodType);
		  
		  for (int count = 0; count < headersList.size(); count++)	
			  options.setHeader(headersList.get(count).getName(),headersList.get(count).getValue()) ;
		  
			GadgetsIo  gIO = IoProvider.get();
			loading.start();
			gIO.makeRequestAsJso(url, new ResponseReceivedHandler<JsArray<JavaScriptObject>>() {
		        @Override
				public void onResponseReceived(
		                ResponseReceivedEvent<JsArray<JavaScriptObject>> event) {
		              Response<JsArray<JavaScriptObject>> response = event.getResponse();
		              if (response!=null && response.getData()!=null){
		            	  loading.stop();
		            	 
		            	 if(handler!=null)
		            		 handler.onSuccess(response.getData());
		            	 else{
		            		 parseJson(response.getData());
		            		 processResults();
		            	 }
		            		
		            	
		              }
		                	
		              else if (response!=null && response.getOauthApprovalUrl()!=null){
		              	  
		            	  loading.stop();
		            	  new OauthApprovalPopUp().approveOAuth(response.getOauthApprovalUrl(), getRequest(), handler,authorizationMsg);
	            	  
		             }
		              else{
		            	  errorNotifier.showError(1, response.getOauthError()+response.getOauthErrorText()) ;      	 		            	 	                  
		            	  loading.stop();
		            	  handler.onError(response.getErrors());
		              }
		            	   
		            }
		        	
		          },options);
		
			return true;
	}
	
	
	protected  void parseJson(JsArray<JavaScriptObject> data) {
		
		JSONArray entryArray = null;
		JSONObject entry = null;
				 
		try 
		{
		if((new JSONObject(data)).get("feed")!=null && (new JSONObject(data)).get("feed").isObject().get("entry")!=null)
		  entryArray = (new JSONObject(data)).get("feed").isObject().get("entry").isArray();
		else
			entryArray = null;
		}
		catch (Exception e) 
		{
			errorNotifier.showError(1,e.getMessage()) ;      	 
		}
		//skip if no records
		if(entryArray!=null)	
		 for(int i=0;i<entryArray.size();i++)
		 {
			 try 
			 {
				// check for name, if name valid then add
				 entry = entryArray.get(i).isObject();
				 if(entry.get("title")!=null && !entry.get("title").isObject().get("$t").isString().stringValue().isEmpty())
						addItem(entry); 
			 }
			 catch (Exception e) 
			 {
				 errorNotifier.showError(1,e.getMessage()) ; 
			 } 
		}
		 
	}
	
	protected  void processResults() {};

	private  class Headers{
		public String getName() {
			return name;
		}

		public String getValue() {
			return value;
		}

		private String name;
		private String value;
		
		Headers(String name, String value){
			this.name = name;
			this.value = value;
		}
	}
		
}

